package org.zjt.scala.pattern

/**
  *
  * Description: 
  *
  * @author juntao.zhang
  *         Date: 2018-06-25 下午1:59
  * @see
  */
class Example {

  // 输入为 any，输出为 Unit
  type pf = PartialFunction[Any, Unit]


  def methodMatch1(arg:Any) = arg match {
    case y: String => println("字符串:%s".format(y))
    case y: Int => println("整型:%s".format(y))
    case _ => println("未知类型")
  }


  // 操作符重载
  def + (i:Int): Unit ={
    println("操作符+重载：i = %s",i)
  }


  // 偏函数例子,  receive 属于 pf 函数
  def receive:pf = {
    case "printit" => println("-------------")
    case _ => println("undefined")
  }


  // 柯里化
  def add(x:Int)(y:Int) = {x + y}


  // 匹配模式
  def methodMatch2(x:String) = {
    x match {
      case "zhang" => println("zhangsan")
      case "li" => println("lisi")
      case _ => println("nobody")
    }
  }


  def methodMatch3(x:String) = {
    val result = x match {
      case "zhang" => x + "san"
      case "li" => "lisi"
      case _ => "nobody"
    }
    result
  }


  //可变参数
  def printStrings(args:String*):Unit ={
    for(arg <- args){
      println(arg)
    }
  }


  // 传递函数的引用    高阶函数（Higher-Order Function）就是操作其他函数的函数。
  def apply(f: Int => String , v:Int) = f(v)


  // 嵌套方法
  def sum(nums:Int *): Int ={

    def add(x:Int,y:Int): Int = x + y

    var total = 0 ;
    for(num <- nums){
      total = add(num,total)
    }
    total
  }


}


/**
  * object 为 class Example的静态内容
  */
object Example {

  def main(args: Array[String]): Unit = {
    val example = new Example()
    example.methodMatch1(111)
    example + 1

    example.receive(1)

    val  add = example.add(1)(_:Int)
    println(add(2))


    example.printStrings("ssss","2222222")


    println(example.apply(x => "产生的字符串:%s".format(x),222))

    println(example.sum(1,2,3,4,5))

  }


}
